package com.cn.dream_order_server.controller;

import com.cn.dream_order_server.config.PaypalPaymentIntent;
import com.cn.dream_order_server.config.PaypalPaymentMethod;
import com.cn.dream_order_server.pojo.OrderOrder;
import com.cn.dream_order_server.pojo.PaypalService;
import com.cn.dream_order_server.service.OrderOrderBackstageService;
import com.cn.dream_order_server.service.OrderOrderService;
import com.cn.dream_order_server.util.URLUtil;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**   
* @author xsansan  
* @date 2018年9月12日 
* Description:  
*/
@Controller
public class PaymentController {




    public static final String PAYPAL_SUCCESS_URL = "paySuccess";
    public static final String PAYPAL_CANCEL_URL = "cancel";

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private PaypalService paypalService;

    @Autowired
    private OrderOrderBackstageService orderOrderBackstageService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/toPayIndex",method = RequestMethod.GET)
    public String toPayIndex(String orderId, Map map){
        OrderOrder orderOrder = orderOrderBackstageService.getOrderOrderByOrderId(orderId);
        map.put("orderOrder",orderOrder);
        return "team";
    }

    @RequestMapping(method = RequestMethod.POST,value = "pay")//
    public String pay(HttpServletRequest request,Integer orderTotal,String orderId) {
        String cancelUrl = URLUtil.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
        String successUrl = URLUtil.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;
        Double total = Double.valueOf(orderTotal.toString())*0.01;
        try {
        	// Create payment
            Payment payment = paypalService.createPayment(
                    total,
                    "USD",
                    PaypalPaymentMethod.paypal,
                    PaypalPaymentIntent.sale,
                    "payment description", 
                    cancelUrl, 
                    successUrl);
            System.out.println("createPayment=" + payment);
            for(Links links : payment.getLinks()){
                if(links.getRel().equalsIgnoreCase("approval_url")) {
                    stringRedisTemplate.opsForValue().set("payServer-"+payment.getId(),orderId,30,TimeUnit.MINUTES);
                    return "redirect:" + links.getHref();
                }
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            System.out.println(e.getDetails());
        }
        return "redirect:/";
    }

    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
    public String cancelPay() {
        return "cancel";
    }

    @RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
    public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId,Map map) {
        try {
        	System.out.println("paymentId=" + paymentId + ",payerId=" + payerId);
            Payment payment = paypalService.executePayment(paymentId, payerId);
            System.out.println("payment" + payment);
            if(payment.getState().equals("approved")) {
                String s = stringRedisTemplate.opsForValue().get("payServer-" + payment.getId());
                if (s!=null&&!"".equals(s)){
                    OrderOrder orderOrder = orderOrderBackstageService.getOrderOrderByOrderId(s);
                    if(orderOrder!=null){
                        orderOrder.setPaytypeId("1");
                        orderOrder.setPayTime(new Date());
                        orderOrder.setPayMode("3");
                        orderOrder.setSerialNumber(payment.getId());
                        orderOrder.setOrdertypeId("2");
                        orderOrder.setOrderOther4(3);
                        orderOrderBackstageService.baseUpdateOrderOrderByOrderId(orderOrder);
                        String s1 = stringRedisTemplate.opsForValue().get("create-order-" + orderOrder.getOrderId());
                        if (s1!=null&&!"".equals(s1)){
                            stringRedisTemplate.delete("create-order-" + orderOrder.getOrderId());
                        }

                    }
                    System.out.println(orderOrder);
                    map.put("orderOrder",orderOrder);
                }
                return "paySuccess";
            }
        } catch (PayPalRESTException e) {
            log.error(e.getMessage());
            System.out.println(e.getDetails());
        }
        return "redirect:/";
    }

}
